package SerialTest1;

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.table.*;
import javax.swing.*;

public class ListGUI implements ActionListener {
	

	public JTable table;
	public JScrollPane scrollPane;
	public JPanel panel;
	public JPanel orderPanel;
	public JButton Addbtn;
	public JButton Deletebtn;
	public JButton Upbtn;
	public JButton Downbtn;
	public JPanel optionPanel;
	public static JComboBox comboBox;
	public JLabel lb;
	public JPanel btnPanel;
	public static JFileChooser fc;
	public static File file = null;
	public static FileReader fr = null;
	public static ChatGUI cg = new ChatGUI();
	public static ConfigGUI fg;
	public static SerialDemo sd = new SerialDemo();
	public ImageIcon icon;
	public static int row = 0;
	public static int column = 0;
	public static StringBuffer str = null;
	public static String result = "";
	public static SerialParameters parameters = new SerialParameters();
	public static SerialConnection sc = new SerialConnection(sd, parameters);

	public ListGUI() {

		table = new JTable(new ExampleTableModel());
		scrollPane = new JScrollPane(table);
		btnPanel = new JPanel(new GridLayout(1, 2));
		table.setFillsViewportHeight(true);
		table.setBackground(new Color(220, 240, 220));
		Addbtn = new JButton("Add");
		Deletebtn = new JButton("Delete");

		Upbtn = new JButton(new ImageIcon("Upbtn.jpg"));
		Downbtn = new JButton(new ImageIcon("Downbtn.jpg"));
		orderPanel = new JPanel(new GridLayout(1, 2));
		orderPanel.add(Upbtn);
		orderPanel.add(Downbtn);
		optionPanel = new JPanel(new BorderLayout());

		lb = new JLabel("Send List");
		lb.setHorizontalAlignment(SwingConstants.CENTER);
		btnPanel.add(Addbtn);
		btnPanel.add(Deletebtn);
		//panel = new JPanel(new BorderLayout());
		icon = new ImageIcon("gridwiz1.jpg");

		panel = new JPanel(new BorderLayout()) {
			public void paintComponent(Graphics g) {
				Graphics2D g2d = (Graphics2D) g;
				// Approach 1: Dispaly image at at full size
				g2d.drawImage(icon.getImage(),0, 0, null);
				g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
				// Approach 2: Scale image to size of component
				// Dimension d = getSize();
				// g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
				// Approach 3: Fix the image position in the scroll pane
				// Point p = scrollPane.getViewport().getViewPosition();
				// g.drawImage(icon.getImage(), p.x, p.y, null);
				setOpaque(false);
				super.paintComponent(g2d);
			}
		};
		String[] name = {"ASCII","Hex"};
		comboBox = new JComboBox(name);
		comboBox.setSelectedIndex(0);

		table.getColumn("Type").setCellEditor(new DefaultCellEditor(comboBox));
		table.getColumn("File").setCellRenderer(new FileButtonCellRenderer());
		table.getColumn("File").setCellEditor(new FileButtonCellEditor());
		table.getColumn("Send").setCellRenderer(new SendButtonCellRenderer());
		table.getColumn("Send").setCellEditor(new SendButtonCellEditor());
		table.getColumn("Type").setPreferredWidth(20);
		table.getColumn("File").setPreferredWidth(10);
		table.getColumn("Message").setPreferredWidth(330);
		table.getColumn("Send").setPreferredWidth(50);
		optionPanel.add(btnPanel, "Center");
		optionPanel.add(orderPanel, "East");
		panel.add(lb, "North");
		panel.add(scrollPane, "Center");
		panel.add(optionPanel, "South");
		
		


		Addbtn.addActionListener(this);
		Deletebtn.addActionListener(this);
		Upbtn.addActionListener(this);
		Downbtn.addActionListener(this);
	}

	public static void main(String[] args) {
		new ListGUI();
	}

	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		Object obj = e.getSource();
		int row = table.getRowCount() + 1;
		if (cmd.equals("Add")) {
			TableModel model = table.getModel();
			if (model instanceof DefaultTableModel) {
				((DefaultTableModel) model).addRow(new Object[] {
						"ASCII", "... ", " " });
			}
		}
		if (cmd.equals("Delete")) {
			try {
				TableModel model = table.getModel();
				((DefaultTableModel) model).removeRow(table.getSelectedRow());
			} catch (ArrayIndexOutOfBoundsException ec) {
				System.out.println("You must select the row.");
			}
		}
		if ((JButton) obj == Upbtn) {
			TableModel model = table.getModel();
			String s = (String) ((DefaultTableModel) model).getValueAt(
					table.getSelectedRow(), 2);
			String as = (String) ((DefaultTableModel) model).getValueAt(
					table.getSelectedRow() - 1, 2);
			if (table.getSelectedRow() != 0)
				((DefaultTableModel) model).setValueAt(s,
						table.getSelectedRow() - 1, 2);
			((DefaultTableModel) model).setValueAt(as, table.getSelectedRow(),
					2);
			// table.clearSelection();
			table.setRowSelectionInterval(table.getSelectedRow() - 1,
					table.getSelectedRow() - 1);
		}
		if ((JButton) obj == Downbtn) {
			TableModel model = table.getModel();
			String s = (String) ((DefaultTableModel) model).getValueAt(
					table.getSelectedRow(), 2);
			String as = (String) ((DefaultTableModel) model).getValueAt(
					table.getSelectedRow() + 1, 2);
			if (table.getSelectedRow() != table.getRowCount())
				((DefaultTableModel) model).setValueAt(s,
						table.getSelectedRow() + 1, 2);
			((DefaultTableModel) model).setValueAt(as, table.getSelectedRow(),
					2);
			// table.clearSelection();
			table.setRowSelectionInterval(table.getSelectedRow() + 1,
					table.getSelectedRow() + 1);
		}

	}

	public static class ExampleTableModel extends DefaultTableModel {

		public ExampleTableModel() {
			super(new Object[] { "Type", "File", "Message", "Send" }, 0);
			for (int index = 0; index < 10; index++) {
				addRow(new Object[] { "ASCII" , "...", "" });
			}
		}

		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			return true;
		}

	}


	public static class FileButtonCellEditor extends AbstractCellEditor
			implements TableCellEditor {

		private JButton editor;
		private Object value;
		private int row;
		private JTable table;

		public FileButtonCellEditor() {
			editor = new JButton();
			editor.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					fc = new JFileChooser("./");
					if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
						try {
							file = fc.getSelectedFile();
							fr = new FileReader(file);
							table.setValueAt(file.getPath(), row, 2);

						} catch (Exception ex) {
						}
					}
				}
			});

		}

		@Override
		public boolean isCellEditable(EventObject e) {
			return true;
		}

		@Override
		public Object getCellEditorValue() {
			return value;
		}

		@Override
		public Component getTableCellEditorComponent(JTable table,
				Object value, boolean isSelected, int row, int column) {
			this.table = table;
			this.row = row;
			this.value = value;
			if (value != null) {
				editor.setText("F");
			} else {
				editor.setText("F");
			}
			if (isSelected) {
				editor.setForeground(table.getSelectionForeground());
				editor.setBackground(table.getSelectionBackground());
			} else {
				editor.setForeground(table.getForeground());
				editor.setBackground(UIManager.getColor("Button.background"));
			}
			return editor;
		}
	}

	public static class FileButtonCellRenderer extends JButton implements
			TableCellRenderer {

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			if (value != null) {
				setText("F");
			} else {
				setText("F");
			}
			if (isSelected) {
				setForeground(table.getSelectionForeground());
				setBackground(table.getSelectionBackground());
			} else {
				setForeground(table.getForeground());
				setBackground(UIManager.getColor("Button.background"));
			}
			return this;
		}
	}

	public static class SendButtonCellRenderer extends JButton implements
			TableCellRenderer {

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			if (value != null) {
				setText("Send");
			} else {
				setText("Send Data");
			}
			if (isSelected) {
				setForeground(table.getSelectionForeground());
				setBackground(table.getSelectionBackground());
			} else {
				setForeground(table.getForeground());
				setBackground(UIManager.getColor("Button.background"));
			}
			return this;
		}
	}

	public static class SendButtonCellEditor extends AbstractCellEditor
			implements TableCellEditor {

		public JButton editor;
		private Object value;
		private int row;
		private JTable table;

		public SendButtonCellEditor() {
			editor = new JButton();
			editor.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					table.setRowSelectionInterval(table.getSelectedRow(),
							table.getSelectedRow());
					BufferedReader br = null;
					BufferedWriter bw = null;
					String string;
					try {
						str = new StringBuffer();
						int count = table.getSelectedRow();
						String dir = String.valueOf(table.getValueAt(count, 2));
						File f = new File(dir);
						// file = fc.getSelectedFile();
						fr = new FileReader(f);
						int i = 0;
						while ((i = fr.read()) != -1)
							str.append((char) i);
						String sendData = String.valueOf(str);
						
						byte[] buf = null;
						if(table.getValueAt(table.getSelectedRow(), 0).equals("Hex"))
							buf = hexToByteArray(sendData);

						if(table.getValueAt(table.getSelectedRow(), 0).equals("ASCII"))
							buf = sendData.getBytes();
						
						cg.sendData(buf);
						sc.sendString(str);
						TCPServer.sendString(str);
						TCPClient.sendString(str);
						UDP.sendString(str);
						bw = new BufferedWriter(new FileWriter("save"
								+ table.getSelectedRow() + ".txt"));
						bw.write(sendData);
						bw.close();
					} catch (FileNotFoundException ex) {
						byte[] send = null;

						if(table.getValueAt(table.getSelectedRow(), 0).equals("Hex"))
							send = hexToByteArray(String.valueOf(table.getValueAt(row, 2)));

						if(table.getValueAt(table.getSelectedRow(), 0).equals("ASCII"))
							send = (String.valueOf(table.getValueAt(row, 2))).getBytes();
						
						cg.sendData(send);
						StringBuffer sendDataself = new StringBuffer(
								new String(send));
						TCPServer.sendString(sendDataself);
						TCPClient.sendString(sendDataself);
						UDP.sendString(sendDataself);
						sc.sendString(sendDataself);

						try {
							bw = new BufferedWriter(new FileWriter("save"
									+ table.getSelectedRow() + ".txt"));
							bw.write(String.valueOf(table.getValueAt(row, 2)));
							bw.close();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			});
		}

		@Override
		public boolean isCellEditable(EventObject e) {
			return true;
		}

		@Override
		public Object getCellEditorValue() {
			return value;
		}

		@Override
		public Component getTableCellEditorComponent(JTable table,
				Object value, boolean isSelected, int row, int column) {
			this.table = table;
			this.row = row;
			this.value = value;
			if (value != null) {
				editor.setText("Send");
			} else {
				editor.setText("Send Data");
			}
			if (isSelected) {
				editor.setForeground(table.getSelectionForeground());
				editor.setBackground(table.getSelectionBackground());
			} else {
				editor.setForeground(table.getForeground());
				editor.setBackground(UIManager.getColor("Button.background"));
			}
			return editor;
		}

	}
	
	public static byte[] hexToByteArray(String hex) {
	    if (hex == null || hex.length() == 0) {
	        return null;
	    }
	 
	    byte[] ba = new byte[hex.length() / 2];
	    for (int i = 0; i < ba.length; i++) {
	        ba[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
	    }
	    return ba;
	}

}